from exts import db
from datetime import date

class UserModel(db.Model):
    __tablename__ = 'user'
    # 微信登录的openid
    open_id = db.Column(db.String(32), primary_key=True)
    # 用户名
    username = db.Column(db.String(20))
    # 头像图片链接
    avatar = db.Column(db.String(100), default="https://i.postimg.cc/fRMrH6XP/default.png")
    # 用户个人简介
    self_intro = db.Column(db.String(50), default='')
    # 用户生日
    birthday = db.Column(db.Date, default=None)
    # 是否可评论
    allow_comment = db.Column(db.Boolean, default=True, nullable=False)
    # 是否可发表博客
    allow_blog = db.Column(db.Boolean, default=True, nullable=False)
    # 用户角色：管理员、普通用户
    role = db.Column(db.Integer, default=0, nullable=False)

    # 关系
    blogs = db.relationship('BlogModel', back_populates='author', lazy='dynamic')
    starlists = db.relationship('StarListModel', back_populates='user', lazy='dynamic')
    comments = db.relationship('CommentModel', back_populates='user', lazy='dynamic')

    def to_dict(self, choice='user'):
        if choice == 'admin':
            return {c.name: self._convert_value(getattr(self, c.name, None)) for c in self.__table__.columns}
        return {c.name: self._convert_value(getattr(self, c.name, None)) for c in self.__table__.columns if c.name != 'open_id'}

    @staticmethod
    def _convert_value(value):
        if isinstance(value, date):
            return value.strftime('%Y-%m-%d')  # 转换字符串
        return value
